import os
from os.path import join, getsize
import glob
import subprocess
import sys
from tools import *
import time
import re

log = getlogger(__name__)


def main(log_name, proc_pattern, minsize, maxsize, *start_args):
    log_name = os.path.join(BASEDIR, '../', log_name)
    deleted = del_bak_file(log_name, minsize, maxsize)
    if len(deleted) == 0:
        return
    log.info('deleted files %s', str(deleted))
    if proc_pattern is not None and proc_pattern != '':
        log.info('stop procs by pattern : %s', proc_pattern)
        ret = stop_processes_by_pattern(proc_pattern)
        log.info('stop procs result : %s', ret)
        log.info('start proc using : %s', str(start_args))
        return timed_start(start_args, 5)


def del_bak_file(log_file, minsize, maxsize):  # str
    ret = {}
    deleted = []
    for f in glob.glob1(log_file, "*"):
        filePath = os.path.join(log_file, f)
        if re.match(".*?\d$", filePath):
            ret[filePath] = os.stat(filePath)
    totalsize = sum([st.st_size for st in ret.values()])
    log.info(totalsize)
    if totalsize > maxsize * 1024 * 1024:
        file_list = sorted(ret.items(),
                           key=lambda e: e[1].st_mtime,
                           reverse=False)
        for f, st in file_list:
            os.remove(f)
            deleted.append(f)
            totalsize -= st.st_size
            if totalsize < minsize * 1024 * 1024:
                break
    return deleted


CALLBACKS['restart_script'] = lambda ret, job: restart_process(*ret)
